package com.ruoyi.framework.web.service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Streams;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.user.OAAuthenticationException;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.jsonwebtoken.impl.DefaultClaims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 * 
 * @author ruoyi
 */
@Component
public class TokenService
{
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认1天）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TWENTY = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 获取用户身份信息
     * 
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {

                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                Object phone = claims.get(Constants.JWT_OA_PHONE);
                //如果能拿到手机号就是OA账号登录
                if(phone != null){
                    //手机号做缓存唯一key
                    String userKey = getTokenKey(token);
                    LoginUser loginUser = redisCache.getCacheObject(userKey);
                    if(loginUser!=null){
                        return loginUser;
                    }
                    //OA的监狱名称与系统的监狱要能匹配上
                    Object deptName = claims.get(Constants.JWT_OA_DEPT_NAME);
                    //OA的角色名称与系统的角色要能匹配上
                    Object roleNames = claims.get(Constants.JWT_OA_ROLES);
                    Object userName = claims.get(Constants.JWT_OA_USER_NICK_NAME);
                    SysDept dept = deptService.selectDeptByDeptName(deptName.toString());
                    if(dept == null){
                        throw new OAAuthenticationException(deptName+"单位信息不存在");
                    }
                    String[] roleNamesArray = roleNames.toString().split(",");
                    if (roleNamesArray.length == 0){
                        throw new OAAuthenticationException("OA角色信息不存在");
                    }
                    List<SysRole> roles = roleService.selectRoleByRoleName(roleNamesArray);
                    if(roles.size() != roleNamesArray.length){
                        String strDeptName = dept.getDeptName();
                        Set<String> nameSet = roles.stream().map(SysRole::getRoleName).collect(Collectors.toSet());
                        String[] nonNames = Stream.of(roleNamesArray).filter(t -> !nameSet.contains(t) && t.startsWith(strDeptName)).map(t -> t.substring(strDeptName.length())).toArray(String[]::new);
                        if(nonNames.length > 0) {
                            roles.addAll(roleService.selectRoleByRoleName(nonNames));
                        }
                    }
                    if(roles.size() != roleNamesArray.length){
                        throw new OAAuthenticationException("未找到对应OA角色信息");
                    }
                    //解析token
                    //判断手机号是否存在数据库的用户表
                    SysUser user = userService.getUserByPhone(phone.toString());
                    if(user == null) {
                        user = new SysUser();
                        user.setUserName(phone.toString());
                        user.setNickName(userName.toString());
                        user.setDeptId(dept.getDeptId());
                        user.setPhonenumber(phone.toString());
                        user.setDept(dept);
                        user.setDelFlag("0");
                        user.setStatus("0");
                        user.setCreateBy("oa");
                        user.setRoles(roles);
                        user.setPassword("--------");
                        user.setLoginDate(new Date());
                        user.setPwdUpdateDate(new Date());
                        String ip = IpUtils.getIpAddr();
                        user.setLoginIp(ip);
                        userService.insertUser(user);
//                        for(SysRole role : roles){
//                            roleService.insertAuthUsers(role.getRoleId(),new Long[]{user.getUserId()});
//                        }
                    }
                    userService.insertUserAuth(user.getUserId(), roles.stream().map(SysRole::getRoleId).toArray(Long[]::new));
                    // 重新查询用户信息，确保获取到最新数据
                    user.setRoles(roles);
                    loginUser = new LoginUser(user.getUserId(), dept.getDeptId(), user, permissionService.getMenuPermission(user));
                    loginUser.setToken(token);
                    refreshToken(loginUser);
                    return loginUser;

                }else{
                    //若依的登录
                    String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                    String userKey = getTokenKey(uuid);
                    LoginUser user = redisCache.getCacheObject(userKey);
                    return user;
                }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     * 
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser)
    {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        claims.put(Constants.JWT_USERNAME, loginUser.getUsername());
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     * 
     * @param loginUser 登录信息
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TWENTY)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     * 
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     * 
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        Claims claims = null;
        try{
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.error("非当前系统默认Token");
            try{
                claims =parseOAToken(token);

            }catch (Exception ex){
                log.error("Token解析失败，既不是系统token也不是OA系统token: {}", ex.getMessage());
            }
        }

        return claims;
    }


    /**
     * 解析OA系统生成的token
     *
     * @param token OA系统生成的token
     * @return Claims
     */
    private Claims parseOAToken(String token) {
        try {
            // 分割 JWT
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                throw new IllegalArgumentException("Invalid JWT token.");
            }

            // Base64URL 解码 payload
            String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]));

            // 输出 JSON 字符串
            System.out.println("Payload JSON: " + payloadJson);

            // 如果需要转为 JSONObject
            Map<String, Object> payload = JSONObject.parseObject(payloadJson);


            // 将com.auth0.jwt的Claims转换为io.jsonwebtoken的Claims格式
            DefaultClaims claims = new DefaultClaims();
//
//            // 添加自定义claims
//            java.util.Map<String, com.auth0.jwt.interfaces.Claim> payloadClaims = jwt.getClaims();
            for (java.util.Map.Entry entry : payload.entrySet()) {
                claims.put(entry.getKey().toString(), entry.getValue());
            }

            return claims;
        } catch (Exception e) {
            log.error("解析OA token失败: {}", e.getMessage());
            throw new RuntimeException("无法解析OA系统token", e);
        }
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }

        //如果是OA的内容  就解析OA的token 再做分析处理


        return token;
    }

    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}
